package com.lw.sbdemo2.service;

import com.github.pagehelper.PageHelper;
import com.lw.sbdemo2.common.base.CrudService;
import com.lw.sbdemo2.common.utils.IdUtils;
import com.lw.sbdemo2.common.utils.ValidUtil;
import com.lw.sbdemo2.common.vo.PageInfo;
import com.lw.sbdemo2.entity.TkExamProductDetail;
import com.lw.sbdemo2.entity.TkExamProductMaster;
import com.lw.sbdemo2.entity.TkUserErrorExamDetail;
import com.lw.sbdemo2.entity.TkUserExamRecord;
import com.lw.sbdemo2.mapper.TkExamProductDetailMapper;
import com.lw.sbdemo2.mapper.TkExamProductMasterMapper;
import com.lw.sbdemo2.mapper.TkUserErrorExamDetailMapper;
import com.lw.sbdemo2.mapper.TkUserExamRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>标题: 试卷商品主表服务 - 业务逻辑层</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2019</p>
 * <p>公司: 山人行工作室</p>
 *
 * @version: 1.0
 * @author: LinWang
 * @date 2019-4-14
 */
@Slf4j
@Service
public class TkExamProductMasterService extends CrudService<TkExamProductMaster, TkExamProductMasterMapper> {

    // private static final Logger log = LoggerFactory.getLogger(TkExamProductMasterService.class);

    @Autowired
    private TkExamProductDetailMapper examProductDetailMapper;

    @Autowired
    private TkBasicDictService tkBasicDictService;

    @Autowired
    private TkUserErrorExamDetailMapper tkUserErrorExamDetailMapper;

    @Autowired
    private TkUserExamRecordMapper tkUserExamRecordMapper;

    /**
     * 获取用户分页列表
     *
     * @param query    搜索关键词
     * @param pageInfo 分页实体
     * @param tkExamProductMaster 实体入参
     * @return 用户列表
     */
    public PageInfo<TkExamProductMaster> findListPage(String query, PageInfo pageInfo, TkExamProductMaster tkExamProductMaster) {
        PageHelper.startPage(pageInfo);
        List<TkExamProductMaster> tkExamProductMasterlist = this.dao.findListPage(query, tkExamProductMaster);
        return new PageInfo<>(tkExamProductMasterlist);
    }

    /**
     * 删除试题相关信息
     *
     * @param tkExamProductMaster
     */
    public void deleteDetail(TkExamProductMaster tkExamProductMaster) throws Exception {

        String examId = tkExamProductMaster.getExamId();
        TkUserErrorExamDetail tkUserErrorExamDetail =
            TkUserErrorExamDetail.builder().examId(examId).build();
        TkUserExamRecord tkUserExamRecord = TkUserExamRecord.builder().examId(examId).build();
        tkUserErrorExamDetailMapper.deleteExam(tkUserErrorExamDetail);
        tkUserExamRecordMapper.deleteUserExam(tkUserExamRecord);
    }

    /**
     * 导入试卷商品主表细表详细信息
     *
     * @param filename
     * @param inputStream
     */
    public void importExcel(String examId, String filename, InputStream inputStream) throws Exception {

        /*if (!filename.endsWith(".xlsx")) {
            throw new Exception("导入格式不正确");
        }*/
        Workbook wb = null;

        try {
            File file = new File("excel");
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            inputStream.close();
            FileInputStream is = new FileInputStream(file);
            if (filename.endsWith("xlsx")) {
                wb = new XSSFWorkbook(is);
            } else if (filename.endsWith("xls")){
                wb = new HSSFWorkbook(is);
            } else {
                throw new Exception("导入格式不是EXECL格式");
            }

            Integer valueInit = 0;
            Integer examScore = 0;
            Double passingScore = 0.0;

           /* Integer[] y = new Integer[]{0, 1, 2, 3, 4, 5, 6, 7, 8};
            List<Integer> sheetArr = new ArrayList<>(Arrays.asList(y));*/
            List<TkExamProductDetail> examProductDetailList = new ArrayList<>();

            //循环sheet页面获取数据
            for (int a = 0; a < wb.getNumberOfSheets(); a++) {
                int sheetNum = 0;
                Sheet sheet = wb.getSheetAt(a);

                //得到Excel的行数
                int totalRows = sheet.getPhysicalNumberOfRows();
                //得到Excel的列数(前提是有行数)
                //判断行数大于一，并且第一行必须有标题
                // if (totalRows >= 1 && sheet.getRow(0) != null) {
                //     totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
                // } else {
                //     throw new Exception("第1行标题不能为空");
                // }
                String questionName = "";
                questionName =  sheet.getSheetName();

                //循环Excel行数,从第二行开始。标题不入库
                for (int r = 1; r < totalRows; r++) {
                    Row row = sheet.getRow(r);
                    Integer b = r + 1 ;
                    if (row == null) {
                        continue;
                    }
                    TkExamProductDetail examProductDetail = new TkExamProductDetail();
                    // if (row.getCell(0) != null) {
                    //     row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                    valueInit += 1;
                        examProductDetail.setQuestionNumber(valueInit);
                    // }

                    if (row.getCell(1) != null) {
                        row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                        String questionBody = row.getCell(1).getStringCellValue();
                        if (!ValidUtil.isNotEmptyAndNull(questionBody)) {
                            continue;
                        }
                        switch(a){
                            case 0 :
                            case 1 :
                            case 2 :
                            case 3 :
                            case 4 :
                            case 6 :
                            case 8 :
                                if (questionBody.indexOf("_") < 0) {
                                    throw new Exception(questionName + "第" + b + "行的题目未包含下划线！");
                                }
                            break;
                            default:
                             break;
                        }
                        examProductDetail.setQuestionBody(row.getCell(1).getStringCellValue());
                    } else {
                        if (a != 7) {
                            continue;
                        }
                    }

                    if (row.getCell(2) != null) {
                        String correctAnswer = row.getCell(2).getStringCellValue();
                        String[] resultArr;
                        List<String> resultArrNew = new ArrayList<>();
                        String resultStr = "";
                        if (correctAnswer.indexOf("#") < 0) {
                            resultStr = StringUtils.trim(correctAnswer);
                        } else {
                            resultArr =  correctAnswer.split("#");
                              for (String temp :resultArr){
                                  resultArrNew.add(StringUtils.trim(temp));
                              }
                              if (resultArrNew.size() > 0) {
                                  resultStr =  String.join("#" ,resultArrNew);
                              }
                        }
                        examProductDetail.setCorrectAnswer(resultStr);
                    } else {
                        if (a == 7) {
                            continue;
                        }

                        throw new Exception(questionName + "第" + b + "行的答案不能为空");
                    }
                    if (row.getCell(3) != null) {
                        row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                        examProductDetail.setAnswerParsing(row.getCell(3).getStringCellValue());
                    }  else {
                        examProductDetail.setAnswerParsing("暂无答案解析");
                    }
                    if (row.getCell(4) != null) {
                        row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                        examProductDetail.setQuestionScore(row.getCell(4).getStringCellValue());
                        String score = row.getCell(4).getStringCellValue();

                        if (ValidUtil.isNotEmptyAndNull(score)) {
                            try {
                                examScore += Integer.parseInt(row.getCell(4).getStringCellValue());
                            } catch (Exception e) {
                                log.error("答案字符串转整数解析出错 {}" ,e.getMessage());
                                throw new Exception(questionName + "第" + b + "行的得分输入格式错误");
                            }
                        } else {
                            examProductDetail.setQuestionScore("1");
                            examScore += 1;
                        }
                    } else {
                        examProductDetail.setQuestionScore("1");
                        examScore += 1;
                    }

                    if (row.getCell(5) != null) {
                        examProductDetail.setQuestionOptions(row.getCell(5).getStringCellValue());
                    }

                    if (row.getCell(5)  == null && (a > 3 && a < 8)) {
                        b = r + 1 ;
                        throw new Exception(questionName + "第" + b + "行的选项不能为空");
                    }

                    if (row.getCell(6) != null) {
                        examProductDetail.setQuestionDetail(row.getCell(6).getStringCellValue());
                    }

                    if (row.getCell(6)  == null && (a == 7)) {
                        b = r + 1 ;
                        throw new Exception(questionName + "第" + b + "行的子题目不能为空");
                    }

                    examProductDetail.setQuestionId(IdUtils.uuid());
                    examProductDetail.setQuestionType(String.valueOf(a));
                    examProductDetail.setExamId(examId);
                    examProductDetail.setValidFlag("1");
                    examProductDetail.setQuestionName(questionName);
                    examProductDetail.setCreatedTime(new Date());
                    examProductDetailList.add(examProductDetail);
                }
            }

            TkExamProductDetail examProductDetail = TkExamProductDetail.builder().examId(examId).build();
            examProductDetailMapper.delete(examProductDetail);

            //删除用户答题细表记录
            TkUserErrorExamDetail tkUserErrorExamDetail =
                TkUserErrorExamDetail.builder().examId(examId).build();
            tkUserErrorExamDetailMapper.deleteExam(tkUserErrorExamDetail);
            //删除用户拥有题库记录
            TkUserExamRecord tkUserExamRecord = TkUserExamRecord.builder().examId(examId).build();
            tkUserExamRecordMapper.deleteUserExam(tkUserExamRecord);

            passingScore = examScore*0.6;
            examProductDetailMapper.insertDetailBatch(examProductDetailList);
            TkExamProductMaster tkExamProductMaster = TkExamProductMaster.builder().examId(examId)
                .totalScore(examScore.longValue()).passingScore(passingScore.longValue()).build();


            this.dao.update(tkExamProductMaster);
        } catch (Exception ex) {
            log.error("导入数据报表解析失败 {}" ,ex.getMessage());
            throw new Exception(ex.getMessage());
        }

    }
}